
<template>
    <input :value="value" type="text" @input="onInput" ref="inputRef" />
</template>
<script>
import { ref } from "vue";
export default {
    name: 'child',
    props: {
        props: {
            value: String,
            maxLength: Number
        },
    },
    setup(props, { emit }) {
        // Vue3中获取组件或者dom实例的一种方式
        const inputRef = ref()
        const value = props.value
        // 限制文字长度
        const limitLength = (value, maxLength) =>
            value.slice(0, maxLength)


        // 输入控制
        const controlled = (value) => {
            inputRef.value.value = value
        }
        const onInput = (e) => {
            let value = e.target.value

            if (typeof props.maxLength === 'number' && props.maxLength >= 0) {
                value = limitLength(value, props.maxLength)
            }

            controlled(value)

            // 向外部返回一个处理过的值
            emit('onInput', value)
        }
        return {
            onInput,
            inputRef,
            value
        }
    }
}
</script>
<style scoped></style>